﻿using GalaSoft.MvvmLight.Messaging;
using PremisPublisher.Messages;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PremisPublisher
{
    /// <summary>
    /// AUTHOR:张鹏
    /// 日期：2016.5
    /// </summary>
    public partial class MainWindow : Window
    {
        private Button CloseButton;
        private Button MinButton;
        private TextBlock WindowTitleTbl;

        private CryptDirectoryFilesWindow _cryptWindow;
        private SQLContentEditorWindow _sqlcontentWindow;
        private PublishLog publicWin;

        public MainWindow()
        {
            InitializeComponent();

            Closed += MainWindow_Closed;
            Loaded += MainWindow_Loaded;

            Messenger.Default.Register<ShowCryptWindowMessage>(this, msg =>
            {
                _cryptWindow = new CryptDirectoryFilesWindow();
                _cryptWindow.Title = msg.Message;
                _cryptWindow.ShowDialog();
            });

            Messenger.Default.Register<ClearUserDomainsMessage>(this, msg =>
            {
                domain_panel.Children.Clear();
            });
            Messenger.Default.Register<HideCryptWindowMessage>(this, msg => { _cryptWindow.Hide(); });
            Messenger.Default.Register<DataSet>(this, FillDataSet);
            Messenger.Default.Register<ShowMessageDialogMessage>(this, ShowMessageDialog);
            Messenger.Default.Register<EditSQLContentMessage>(this, EditSQLContent);

            Messenger.Default.Register<ShowPublishLogWindowMessage>(this, msg =>
            {
                publicWin = new PublishLog();
                Messenger.Default.Send(new SetLogCurrentOperationMessage() { Message = msg.Message });
                publicWin.Show();
            });
            Messenger.Default.Register<HidePublishLogWindowMessage>(this, msg => { publicWin.Hide(); });
            Messenger.Default.Register<PublishDoneWindowMessage>(this, msg =>
            {
                MessageBox.Show(msg.Message);
            });

            Messenger.Default.Register<ShowWindow>(this, w =>
            {
                if (w.WindowWillShow != null)
                    w.WindowWillShow.ShowDialog();
            });
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("PremisPublisher.xml_syntax.xml"))
            {
                using (var reader = new System.Xml.XmlTextReader(stream))
                {
                    this.ava_editor.SyntaxHighlighting =
                ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader,
                ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance);
                }
            }

            // 查找窗体模板
            ControlTemplate metroWindowTemplate
                    = App.Current.Resources["MetroWindowTemplate"] as ControlTemplate;
            if (metroWindowTemplate != null)
            {
                CloseButton = metroWindowTemplate.FindName("CloseWinButton", this) as Button;
                MinButton = metroWindowTemplate.FindName("MinWinButton", this) as Button;
                CloseButton.Click += CloseButton_Click;
                MinButton.Click += MinButton_Click;
                WindowTitleTbl = metroWindowTemplate.FindName("WindowTitleTbl", this) as TextBlock;
                if (WindowTitleTbl != null)
                    WindowTitleTbl.Text = "不动产登记 - 自动发布/升级工具";
            }

            App.splashScreen.LoadComplete();
        }

        private void MinButton_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Minimized;
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {


            Close();
        }

        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            DragMove();
            base.OnMouseLeftButtonDown(e);
        }

        private void FillDataSet(DataSet ds)
        {
            if (ds == null) return;
            MainTab.DataContext = null;

            List<TabItem> tabItems = new List<TabItem>();

            foreach (DataTable table in ds.Tables)
            {
                TabItem tab_item = new TabItem() { Name = table.TableName, Header = table.TableName };

                DataGrid data_grid = new DataGrid()
                {
                    SelectionMode = DataGridSelectionMode.Extended,
                    ItemsSource = table.AsDataView(),
                    IsReadOnly = true
                };

                Style rowStyle = new Style(typeof(DataGridRow));
                rowStyle.Setters.Add(new EventSetter(DataGridRow.MouseDoubleClickEvent,
                                         new MouseButtonEventHandler(Row_DoubleClick)));
                data_grid.RowStyle = rowStyle;

                var context_menu = new System.Windows.Controls.ContextMenu();
                MenuItem item0 = new MenuItem() { Header = "查看" };

                item0.Click += (s, e) =>
                {

                    var view = data_grid.SelectedItem as DataRowView;
                    var domain_flag = view.Row.Table.TableName.Substring(0, 1);
                    var domain_code = view.Row.ItemArray[0].ToString();
                    string domain = domain_flag + domain_code;

                    Messenger.Default.Send(new GetSQLContentMessage() { Message = domain });
                };

                MenuItem item1 = new MenuItem() { Header = "添加全部" };
                item1.Click += (s, e) =>
                {

                    var domain_flag = table.TableName.Substring(0, 1);

                    foreach (DataRow row in table.Rows)
                    {
                        var code = row[0].ToString();
                        string domain = domain_flag + code;

                        TextBlock tb = new TextBlock()
                        {
                            FontSize = 14,
                            Text = domain,
                            Margin = new Thickness(3),
                            Background = new System.Windows.Media.SolidColorBrush(Colors.GreenYellow),
                            Name = domain,
                            AllowDrop = true
                        };

                        Style blockStyle = new Style(typeof(TextBlock));
                        blockStyle.Setters.Add(new EventSetter(TextBlock.PreviewMouseMoveEvent,
                            new MouseEventHandler(TextBlock_PreviewMouseMove)));

                        blockStyle.Setters.Add(new EventSetter(TextBlock.PreviewMouseLeftButtonDownEvent,
                            new MouseButtonEventHandler(TextBlock_PreviewMouseLeftButtonDown)));

                        tb.Style = blockStyle;


                        //去重
                        if (!(this.UpgradeTab.DataContext as PremisPublisher.ViewModel.UpgradeMainViewModel).UserDomains.Contains(domain))
                        {
                            domain_panel.Children.Add(tb);
                            Messenger.Default.Send(domain);
                        }

                    }

                };
                MenuItem item2 = new MenuItem() { Header = "添加选中" };
                item2.Click += (s, e) =>
                {

                    foreach (var item in data_grid.SelectedItems)
                    {
                        var view = item as DataRowView;

                        var domain_flag = view.Row.Table.TableName.Substring(0, 1);

                        var domain_code = view.Row.ItemArray[0].ToString();

                        string domain = domain_flag + domain_code;

                        TextBlock tb = new TextBlock()
                        {
                            FontSize = 14,
                            Text = domain,
                            Margin = new Thickness(3),
                            Background = new System.Windows.Media.SolidColorBrush(Colors.GreenYellow),
                            Name = domain,
                            AllowDrop = true
                        };

                        Style blockStyle = new Style(typeof(TextBlock));
                        blockStyle.Setters.Add(new EventSetter(TextBlock.PreviewMouseMoveEvent,
                            new MouseEventHandler(TextBlock_PreviewMouseMove)));

                        blockStyle.Setters.Add(new EventSetter(TextBlock.PreviewMouseLeftButtonDownEvent,
                            new MouseButtonEventHandler(TextBlock_PreviewMouseLeftButtonDown)));

                        tb.Style = blockStyle;


                        //去重
                        if (!(this.UpgradeTab.DataContext as PremisPublisher.ViewModel.UpgradeMainViewModel).UserDomains.Contains(domain))
                        {
                            domain_panel.Children.Add(tb);
                            Messenger.Default.Send(domain);
                        }
                    }
                };
                context_menu.Items.Add(item0);
                context_menu.Items.Add(item1);
                context_menu.Items.Add(item2);

                data_grid.ContextMenu = context_menu;


                tab_item.Content = data_grid;

                tabItems.Add(tab_item);
            }

            MainTab.DataContext = tabItems;
            MainTab.SelectedIndex = 0;
        }

        void MainWindow_Closed(object sender, EventArgs e)
        {
            Messenger.Default.Unregister<ShowMessageDialogMessage>(this);
            Messenger.Default.Unregister<EditSQLContentMessage>(this);
            Messenger.Default.Unregister<DataSet>(this);
            Messenger.Default.Unregister<HideCryptWindowMessage>(this);
            Messenger.Default.Unregister<ClearUserDomainsMessage>(this);
            Messenger.Default.Unregister<ShowCryptWindowMessage>(this);


            Messenger.Default.Unregister<ShowPublishLogWindowMessage>(this);
            Messenger.Default.Unregister<HidePublishLogWindowMessage>(this);
        }

        private void EditSQLContent(EditSQLContentMessage msg)
        {
            _sqlcontentWindow = new SQLContentEditorWindow();
            _sqlcontentWindow.Title = msg.Title;
            _sqlcontentWindow.model.SQLName = msg.Title;
            _sqlcontentWindow.model.SQLContent.Text = msg.Content;
            _sqlcontentWindow.ShowDialog();
        }

        private void ShowMessageDialog(ShowMessageDialogMessage obj)
        {
            MessageBox.Show(obj.Message);
        }

        private void Row_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            var row = sender as DataGridRow;
            var view = row.Item as DataRowView;
            var domain_flag = view.Row.Table.TableName.Substring(0, 1);
            var domain_code = view.Row.ItemArray[0].ToString();
            string domain = domain_flag + domain_code;

            Messenger.Default.Send(new GetSQLContentMessage() { Message = domain });
        }

        private void TextBlock_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            startPoint = e.GetPosition(titlePanel);
        }

        private void TextBlock_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            Point mousePos = e.GetPosition(null);
            Vector diff = startPoint - mousePos;

            if (e.LeftButton == MouseButtonState.Pressed &&
                Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance &&
                Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance)
            {
                // Initialize the drag & drop operation
                var component = sender as TextBlock;

                DataObject obj = new DataObject(typeof(TextBlock), component);
                DragDrop.DoDragDrop(component, obj, DragDropEffects.All);
            }
        }

        private void StackPanel_DragEnter(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.None;
        }


        private Point startPoint;
        private void StackPanel_Drop(object sender, DragEventArgs e)
        {
            var component = e.Data.GetData(typeof(TextBlock)) as TextBlock;

            var endPoint = e.GetPosition(titlePanel);

            var moveX = endPoint.X - startPoint.X;
            var moveY = endPoint.Y - startPoint.Y;

            var x = Canvas.GetLeft(component) + moveX;
            var y = Canvas.GetTop(component) + moveY;

            Canvas.SetLeft(component, x);
            Canvas.SetTop(component, y);

            domain_panel.Children.Remove(component);
            (this.UpgradeTab.DataContext as PremisPublisher.ViewModel.UpgradeMainViewModel).UserDomains.Remove(component.Name);
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Closing -= Window_Closing;
            e.Cancel = true;
            var anim = new DoubleAnimation(0, (Duration)TimeSpan.FromSeconds(1));
            anim.Completed += (s, _) => this.Close();
            this.BeginAnimation(UIElement.OpacityProperty, anim);
        }

        private void Button_Initialized_1(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            btn.ContextMenu = null;

        }

        private void btnMenu_Click_1(object sender, RoutedEventArgs e)
        {
            this.contextMenu.PlacementTarget = this.btnMenu;
            //位置
            this.contextMenu.Placement = PlacementMode.Top;
            //显示菜单
            this.contextMenu.IsOpen = true;
        }


    }
}
